package com.zanfeng.signleplatform.provider.modules.file;

import com.zanfeng.signleplatform.api.result.modules.resourceFile.ResourceFileResult;
import com.zanfeng.signleplatform.api.service.modules.file.FileService;
import com.zanfeng.signleplatform.common.utils.BeanUtil;
import com.zanfeng.signleplatform.dao.persistence.dao.ResourceFileMapper;
import com.zanfeng.signleplatform.dao.persistence.entity.ResourceFile;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Transactional
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private ResourceFileMapper resourceFileMapper;

    @Override
    public ResourceFileResult findResourceFileResultByMd5(String md5) {
        ResourceFile resourceFile = resourceFileMapper.findResourceFileByMd5(md5);
        if (resourceFile != null) {
            return BeanUtil.cast(resourceFile, ResourceFileResult.class);
        }
        return null;
    }

    @Override
    public List<ResourceFileResult> queryResourceFileResultListByMd5s(String md5s) {
        List<ResourceFileResult> resourceFileResultList = new ArrayList<>();
        if (StringUtils.isNotBlank(md5s)) {
            List<ResourceFile> resourceFileList = resourceFileMapper.queryResourceFileListByMd5List(Arrays.asList(md5s.split(",")));
            if (resourceFileList != null) {
                for (ResourceFile resourceFile : resourceFileList) {
                    resourceFileResultList.add(BeanUtil.cast(resourceFile, ResourceFileResult.class));
                }
            }
        }
        return resourceFileResultList;
    }

    @Override
    public void saveResourceFile(ResourceFileResult result) {
        ResourceFile resourceFile = new ResourceFile();
        resourceFile.setLenght(result.getLenght());
        resourceFile.setMd5(result.getMd5());
        resourceFile.setUrl(result.getUrl());
        resourceFile.setUuid(result.getUuid());
        resourceFile.setName(result.getName());
        resourceFileMapper.insertSelective(resourceFile);
    }
}
